//
//  CJNewVipController.m
//  Boss
//
//  Created by admin on 2018/9/19.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "CJNewVipController.h"
#import "CJFlowLayout.h"
#import "CJNewVipCell.h"
#import "CWCarousel.h"
#import "WYVipList.h"
#import "CJNewVipCollectionCell.h"
#import "WYUserMessage.h"
#import "WYPayController.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import "NSDictionary+ExchangeJson.h"
#import "WYPayAlertTooler.h"
#define kViewTag 666
#define kCount 3
@interface CJNewVipController ()<CWCarouselDatasource, CWCarouselDelegate>
@property (strong, nonatomic) IBOutlet UIScrollView *detailScrollView;
@property (strong, nonatomic) IBOutlet UIView *vipDetailView;

@property (nonatomic,strong)NSArray *imageArray;

@property (strong, nonatomic) IBOutlet UIView *vipListView;

@property (nonatomic, strong) CWCarousel *carousel;
@property (nonatomic, strong) UIView *animationView;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (strong, nonatomic) IBOutlet UIImageView *sVipImageView;

@property (strong, nonatomic) IBOutlet UIImageView *gVipImageView;

@property (strong, nonatomic) IBOutlet UIImageView *dVipImageView;

@property (strong, nonatomic) IBOutlet UIImageView *userImageView;
@property (strong, nonatomic) IBOutlet UILabel *userName;
@property (strong, nonatomic) IBOutlet UILabel *timeLabel;
@property (nonatomic,strong)WYPayController *payVC;
@property (nonatomic,strong)WYUserMessage *userMessage;
@property (nonatomic,strong)WYVipList *list;

@end

@implementation CJNewVipController
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

-(NSArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = @[@"VIP111",@"VIP222",@"VIP333"];
    }
    return _imageArray;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.carousel controllerWillAppear];
    [self loadUserData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WXPaySucess:) name:@"WXPaySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AliPayResult:) name:@"AlipayResult" object:nil];
    
}
-(void)AliPayResult:(NSNotification *)noc
{
    NSDictionary *dic =noc.object[@"result"];
    NSUInteger status = [dic[@"resultStatus"] integerValue];
    if (status==9000) {
        [self loadUserData];
    }else{
        
    }
}
-(void)WXPaySucess:(NSNotification *)noc
{
    [self showSucess];
    [self loadUserData];
    //[self toast:@"购买成功"];
    //  int64_t delayInSeconds = 2.0; // 延迟的时间
    
    /*
     *  delta:
     *
     *  @parameter 1.时间参照，从此刻开始计时
     *  @parameter 2.延时多久，此处为秒级，还有纳秒等: 10ull * NSEC_PER_MSEC
     */
    
    //    __weak typeof(self)weakSelf = self;
    //
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        [weakSelf.navigationController popViewControllerAnimated:YES];
    //    });
    
    
    
}
-(void)loadData
{
    WEAKSELF
    [WYHttpServer getVipListSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
           NSArray *array = [WYVipList getVipListFromJson:response[@"result"]];
            [self.dataArray addObjectsFromArray:array];
            [self.dataArray removeObjectAtIndex:0];
            [weakSelf upDataUI];
            [self.carousel.carouselView reloadData];
        }
    }];
}
-(void)upDataUI
{
    WYVipList *vipList1 = self.dataArray[0];
    [self.sVipImageView sd_setImageWithURL:[NSURL URLWithString:vipList1.comment]];
    
    
    WYVipList *vipList2 = self.dataArray[1];
    [self.gVipImageView sd_setImageWithURL:[NSURL URLWithString:vipList2.comment]];
    
    
    
    WYVipList *vipList3 = self.dataArray[2];
    [self.dVipImageView sd_setImageWithURL:[NSURL URLWithString:vipList3.comment]];
}

-(void)loadUserData
{
    WEAKSELF
    [WYHttpServer getUserMessageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
        if (success) {
            weakSelf.userMessage = [WYUserMessage getUserMessageFromJson:response[@"result"]];
            [WYStoreModule storeUserMessage:weakSelf.userMessage];
            [weakSelf updateUI];
        }
        
    }];
}
-(void)updateUI
{
    [self.userImageView sd_setImageWithURL:[NSURL URLWithString:self.userMessage.url]];
    if (!self.userMessage.vipId.intValue) {
        self.userName.textColor = [UIColor whiteColor];
        self.userName.font = [UIFont systemFontOfSize:16];
        self.userName.text = [NSString stringWithFormat:@"HI,%@,开通会员即可体验巨牛BOSS会员专属权益",self.userMessage.userName];
        self.timeLabel.hidden = YES;
    }else{
        self.userName.textColor = [UIColor whiteColor];
        self.userName.font = [UIFont systemFontOfSize:16];
        self.userName.text = [NSString stringWithFormat:@"%@",self.userMessage.userName];
        self.timeLabel.hidden = NO;
        
        
    }
}

-(void)setupUI
{
    [self.userImageView setCornerRadius:24.f];
    
    
    
    [self configureUI];
    [self wr_setNavBarBackgroundAlpha:0];
    self.vipDetailView.width = kScreenWidth *3;
    self.vipDetailView.height = 400;
    [self.detailScrollView addSubview:self.vipDetailView];
    self.detailScrollView.contentSize = CGSizeMake(0, 400);
}

- (void)configureUI{
    [self.vipListView addSubview:self.animationView];
    CATransition *tr = [CATransition animation];
    tr.type = @"cube";
    tr.subtype = kCATransitionFromRight;
    tr.duration = 0.25;
    [self.animationView.layer addAnimation:tr forKey:nil];
    
   // self.view.backgroundColor = [UIColor whiteColor];
    //    if(self.carousel) {
    //        [self.carousel releaseTimer];
    //        [self.carousel removeFromSuperview];
    //        self.carousel = nil;
    //    }
    
    self.animationView.backgroundColor = [UIColor clearColor];
    CWFlowLayout *flowLayout = [[CWFlowLayout alloc] initWithStyle:CWCarouselStyle_H_2];
    flowLayout.itemWidth =kScreenWidth-45;
    //    /*
    //     使用frame创建视图
    //     */
    //    CWCarousel *carousel = [[CWCarousel alloc] initWithFrame:self.animationView.bounds
    //                                                    delegate:self
    //                                                  datasource:self
    //                                                  flowLayout:flowLayout];
    //    [self.animationView addSubview:carousel];
    
    // 使用layout创建视图(使用masonry 或者 系统api)
    CWCarousel *carousel = [[CWCarousel alloc] initWithFrame:CGRectZero
                                                    delegate:self
                                                  datasource:self
                                                  flowLayout:flowLayout];
    carousel.translatesAutoresizingMaskIntoConstraints = NO;
    
    [carousel pause];
    [self.animationView addSubview:carousel];
    NSDictionary *dic = @{@"view" : carousel};
    [self.animationView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[view]-0-|"
                                                                               options:kNilOptions
                                                                               metrics:nil
                                                                                 views:dic]];
    [self.animationView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[view]-0-|"
                                                                               options:kNilOptions
                                                                               metrics:nil
                                                                                 views:dic]];
    
    
    carousel.isAuto = NO;
    carousel.autoTimInterval = 2;
    //    carousel.endless = NO;
    carousel.backgroundColor = [UIColor clearColor];
    
    /* 自定pageControl */
    
   // CGRect frame = self.animationView.bounds;
    //    if(self.openCustomPageControl) {
    //        CWPageControl *control = [[CWPageControl alloc] initWithFrame:CGRectMake(0, 0, 300, 20)];
    //        control.center = CGPointMake(CGRectGetWidth(frame) * 0.5, CGRectGetHeight(frame) - 10);
    //        control.pageNumbers = 5;
    //        control.currentPage = 0;
    //        carousel.customPageControl = control;
    //    }
  //  [carousel registerViewClass:[UICollectionViewCell class] identifier:@"cellId"];
    [carousel registerNibView:@"CJNewVipCollectionCell" identifier:@"CJNewVipCollectionCell"];
    [carousel freshCarousel];
    self.carousel = carousel;
}
//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//
//}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.carousel controllerWillDisAppear];
}
-(void)scrollDidRollWithIndex:(NSUInteger)index
{
    NSLog(@"=====================%ld",index);
    
    [self.detailScrollView setContentOffset:CGPointMake((index-1)*kScreenWidth, 0) animated:NO];
    self.list = self.dataArray[index-1];
    
}


- (NSInteger)numbersForCarousel {
    return kCount;
}
#pragma mark - Delegate
- (UICollectionViewCell *)viewForCarousel:(CWCarousel *)carousel indexPath:(NSIndexPath *)indexPath index:(NSInteger)index{
    CJNewVipCollectionCell *cell = [carousel.carouselView dequeueReusableCellWithReuseIdentifier:@"CJNewVipCollectionCell" forIndexPath:indexPath];
    WYVipList *list = self.dataArray[indexPath.row-1];
    cell.priceLabel.text = [NSString stringWithFormat:@"%.0f 元/年",list.yearMoney.floatValue/1000.0];
    cell.VipImageView.image =[UIImage imageNamed:self.imageArray[indexPath.row-1]];
    if (indexPath.row==1) {
        cell.priceLabel.textColor = [UIColor hexStringToColor:@"#647180" alpha:1.0];
    }else if (indexPath.row==2){
        cell.priceLabel.textColor = [UIColor hexStringToColor:@"#cc7e00" alpha:1.0];
    }else{
        cell.priceLabel.textColor = [UIColor hexStringToColor:@"#416ed3" alpha:1.0];
    }
    
    
    return cell;
}

- (void)CWCarousel:(CWCarousel *)carousel didSelectedAtIndex:(NSInteger)index {
    NSLog(@"...%ld...", (long)index);
}
- (UIView *)animationView{
    if(!_animationView) {
        self.animationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 180)];
    }
    return _animationView;
}

- (IBAction)buyAction:(id)sender {
    
    WYPayController *pvc = [[WYPayController alloc]init];
    self.payVC = pvc;
    
    //    pvc.payMoney.text = [NSString stringWithFormat:@"支付金额：¥%@",self.money];
    //    self.payVC.payMoney.text = [NSString stringWithFormat:@"支付金额：¥%@",self.money];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
    [[UIApplication sharedApplication].keyWindow addSubview:pvc.view];
    pvc.view.frame = CGRectMake(0, kScreenHeight-370, kScreenWidth, 370);
    WEAKSELF
    pvc.exit = ^(NSString *name) {
        [weakSelf.payVC.view removeFromSuperview];
        [weakSelf.maskView removeFromSuperview];
    };
    pvc.complete = ^(NSString *name, NSString *value) {
        [weakSelf.payVC.view removeFromSuperview];
        [weakSelf.maskView removeFromSuperview];
        [weakSelf buyVIPWithType:name];
        //[weakSelf showLoading:@""];
        
    };
    [pvc setMoney:[NSString stringWithFormat:@"%.2f",self.list.yearMoney.floatValue/1000.0]];
    
    
    
    
    
    
    
}
-(void)buyVIPWithType:(NSString *)type
{
    WEAKSELF
    [WYHttpServer buyVipWithVipID:self.list.id WtihTimeType:@"2" WithPayType:type SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            if ([type isEqualToString:@"2"]) {
                //NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response[@"result"] options:NSJSONReadingMutableContainers error:NULL];
                NSString *jsonStr = response[@"result"];
                NSDictionary *dic =  [NSDictionary dictionaryWithJsonString:jsonStr];
                
                [weakSelf goToWechat:dic];
            }
            if ([type isEqualToString:@"1"]) {
                NSString *orderString = response[@"result"];
                [weakSelf gotoAliPay:orderString];
            }
            
            if ([type isEqualToString:@"3"]) {
                [weakSelf showSucess];
            }
            
            
        }else{
            if ([type isEqualToString:@"3"]) {
                [weakSelf showError];
            }
            
            
            
            
            //[weakSelf toast:errorMessage];
        }
        
        
        
    }];
}
-(void)goToWechat:(NSDictionary *)wechatPayDic
{
    PayReq *req = [[PayReq alloc] init];
    req.openID = [wechatPayDic objectForKey:@"appid"];
    req.partnerId = [wechatPayDic objectForKey:@"partnerid"];
    req.prepayId = [wechatPayDic objectForKey:@"prepayid"];
    // req.package = @"WXpay";
    req.package = [wechatPayDic objectForKey:@"package"];
    req.nonceStr = [wechatPayDic objectForKey:@"noncestr"];
    req.timeStamp = [[wechatPayDic objectForKey:@"timestamp"] intValue];
    req.sign = [wechatPayDic objectForKey:@"sign"];
    [WXApi sendReq:req];
}

-(void)gotoAliPay:(NSString *)orderString
{
    NSLog(@"%@",orderString);
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:@"BOSS" callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
    }];
    
    
}

-(void)showSucess
{
    WEAKSELF
    [[WYPayAlertTooler sharedInstance] showAlertTitle:@"付款成功啦" message:@"" imageName:@"pay_success_icon" btnTitles:@"我知道了" btnClicked:^(NSInteger index) {
        // NSLog(@"%ld",index);
        [weakSelf loadUserData];
    }];
}
-(void)showError
{
    [[WYPayAlertTooler sharedInstance] showAlertTitle:@"支付失败咯" message:@"支付遇到问题，请尝试重新支付" imageName:@"pay_error_icon" btnTitles:@[@"放弃",@"重新支付"] btnClicked:^(NSInteger index) {
        NSLog(@"%ld",index);
    }];
}

@end
